package com.pmsco.pms.util;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import com.pmsco.pms.core.constant.PmsConstant;

/**
 * 
 */

/**
 * @author Long Tran
 *
 */
public class PmsMailSender {
	private static PmsMailSender instance = null;
	
	public static PmsMailSender getInstance() {
		if(instance == null)
			instance = new PmsMailSender();
		return instance;
	}
	 
	private PmsMailSender() {
	}
 
	public void sendMail(String from, String to, String subject, String msg) {
		final String username = PmsSysInfo.getInstance().getSysEmailUser();
        final String password = PmsSysInfo.getInstance().getSysEmailPassword();

        Properties props = new Properties();
        props.put("mail.smtp.auth", PmsConstant.enableEmailAuth.equalsIgnoreCase(PmsSysInfo.getInstance().getSysEmailAuth()) ? "true" : "false");
        props.put("mail.smtp.starttls.enable", PmsConstant.enableEmailTls.equalsIgnoreCase(PmsSysInfo.getInstance().getSysEmailTlsEnable()) ? "true" : "false");
        props.put("mail.smtp.host", PmsSysInfo.getInstance().getSysEmailHost());
        props.put("mail.smtp.port", String.valueOf(PmsSysInfo.getInstance().getSysEmailPort()));

        Session session = Session.getInstance(props, 
            new javax.mail.Authenticator() {
                @Override
				protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(username, password);
                }
            }
        );

        try {

            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(from));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
            message.setSubject(subject);
            message.setContent(msg, "text/html");

            Transport.send(message);
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }	
	}
}
